package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.tanhua.common.exception.BusinessException;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.oss.OssTemplate;
import com.tanhua.server.enums.IdType;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
public class VideoService {

    @Reference
    private VideoApi videoApi;

    @Reference
    private QuanZiApi quanZiApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private QuanZiService quanZiService;

    //保存视频
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) {
        try {
            //1.解析token 获取user对象
            User user = UserThreadLocal.get();
            //上传封面 获得封面路径
            String picUrl = ossTemplate.upload(videoThumbnail);
            //上传视频 获得视频路径
            String videoUrl = ossTemplate.upload(videoFile);
            //创建Video对象
            Video video = new Video();
            //封装video的数据
            video.setUserId(user.getId());
            video.setVideoUrl(videoUrl);
            video.setPicUrl(picUrl);
            video.setCreated(System.currentTimeMillis());
            video.setVid(idService.createId(IdType.VIDEO));
            video.setSeeType(1);
            //执行保存
            videoApi.saveVideo(video);

        } catch (Exception e) {
            //视频上传失败异常
            throw new BusinessException(ErrorResult.videoUploadFail());
        }
    }

    //遍历小视频
    public PageResult queryVideo(Integer page, Integer pagesize) {
        //1.解析token
        User user = UserThreadLocal.get();
        //2.查询
        List<Video> lists = videoApi.queryVideo(user.getId(),page, pagesize);
        //3.封装响应的结果集合
        List<VideoVo> list = new ArrayList<>();
        //4.遍历查询到的结果
        for (Video video : lists) {
            VideoVo videoVo = new VideoVo();
            videoVo.setId(video.getId().toHexString());
            //封装封面
            videoVo.setCover(video.getPicUrl());
            //封装视频
            videoVo.setVideoUrl(video.getVideoUrl());
            //5. 通过mbp查询userinfo对象
            LambdaUpdateWrapper<UserInfo> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(UserInfo::getUserId, video.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            //6.添加userinfo对象里的信息 复制到VideoVo
            fileUserInfoToVideoVo(userInfo, videoVo);
            //7.添加videovo到集合中
            list.add(videoVo);
        }
        //8.封装返回前端的对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setItems(list);
        return pageResult;
    }

    //复制userinfo对象里的信息 到VideoVo
    private void fileUserInfoToVideoVo(UserInfo userInfo, VideoVo videoVo) {
        //复制 除了id
        BeanUtil.copyProperties(userInfo, videoVo, "id");
        videoVo.setSignature("合肥JAVA43期狗混子");
        User user = UserThreadLocal.get();
        videoVo.setCommentCount(Convert.toInt(this.quanZiApi.queryCommentCount(videoVo.getId()))); //评论数
        videoVo.setHasFocus(this.videoApi.isFollowUser(user.getId(), videoVo.getUserId()) ? 1 : 0); //是否关注
        videoVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), videoVo.getId()) ? 1 : 0); //是否点赞（1是，0否）
        videoVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(videoVo.getId())));//点赞数

    }

    //小视频点赞
    public Long likeComment(String id) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.likeComment(user.getId(), id);
        if (result) {
            return quanZiApi.queryLikeCount(id);
        }
        return null;
    }

    //小视频取消点赞
    public Long disLikeComment(String id) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.disLikeComment(user.getId(), id);
        if (result) {
            return quanZiApi.queryLikeCount(id);
        }
        return null;
    }

    //评论列表
    public PageResult queryCommentsList(String videoId, Integer page, Integer pageSize) {
        return this.quanZiService.queryCommentList(videoId, page, pageSize);
    }

    //提交评论
    public Boolean saveComment(String videoId, String content) {
        return this.quanZiService.saveComments(videoId, content);
    }

    //关注用户
    public Boolean followUser(Long userId) {
        User user = UserThreadLocal.get();
        return this.videoApi.followUser(user.getId(), userId);
    }

    //取消关注
    public Boolean disFollowUser(Long userId) {
        User user = UserThreadLocal.get();
        return this.videoApi.disFollowUser(user.getId(), userId);
    }

}
